layui.use('table', function () {
    var table = layui.table;

    table.render({
        elem: '#test'
        , url: 'http://localhost:8080/admin/selectlogistic'
        , id: 'logisticId'
        , toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
        , title: '用户数据表'
        , cols: [[
            {type: 'checkbox', fixed: 'left'}
            , {field: 'goodPhoto', title: '商品图片', templet: '#img', width: 100}
            , {field: 'logisticId', title: '物流编号', width: 100,}
            , {field: 'logisticDate', title: '修改日期', width: 100}
            , {field: 'userId', title: '用户ID', width: 90}
            , {field: 'userName', title: '用户昵称', width: 100}
            , {field: 'userPhone', title: '用户电话', width: 100}
            , {field: 'logisticOrderId', title: '订单ID', width: 90}
            , {field: 'logisticLogisticnum', title: '快递单号', width: 100}
            , {field: 'orderState', title: '订单状态', width: 110}
            , {field: 'orderCount', title: '数量', width: 80, sort: true}
            , {field: 'orderMoney', title: '总价', width: 80, sort: true}
            , {field: 'goodName', title: '商品名称', width: 100}
            , {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 150}
        ]]
        , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
            layout: ['prev', 'page', 'next', 'skip', 'count'] //自定义分页布局
            , theme: '#7185a2'
        }
    });

    //头工具栏事件
    table.on('toolbar(test)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'getCheckLength':
                var data = checkStatus.data;
                layer.msg('选中了：' + data.length + ' 个');
                break;
            case 'isAll':
                layer.msg(checkStatus.isAll ? '全选' : '未全选');
                break;
        }
        ;
    });

    //监听行工具事件
    table.on('tool(test)', function (obj) {
        var data = obj.data;
        if (obj.event === 'del') {
            layer.confirm('真的删除行么', function (index) {
                obj.del();
                // console.log("删除按钮点击 物流编号 -> " + obj.data.logisticId)
                dlevalue(obj.data.logisticId)
                layer.close(index);
            });
        } else if (obj.event === 'edit') {
            // 订单ID
            let logisticOrderId = inputvalue(obj.data.logisticOrderId)
            localStorage.setItem("logisticOrderId", logisticOrderId)

            // 快递单号
            let logisticLogisticnum = inputvalue(obj.data.logisticLogisticnum)
            localStorage.setItem("logisticLogisticnum", logisticLogisticnum)

            layer.alert(
                '<form class="layui-form layui-form-pane" action="">\n' +
                '    <div class="layui-form-item">\n' +
                '        <p style="font-size: 15px;color: #6E6E6E;margin-bottom: 3px">顺丰速运 - 申通快递 - 韵达快递</p>\n' +
                '        <label class="layui-form-label" style="width: 117px;">输入快递公司</label>\n' +
                '        <div class="layui-input-block">\n' +
                '            <input type="text" id="comName" name="comName" lay-verify="title" autocomplete="off" placeholder="输入快递公司" class="layui-input" style="width: 206px"></div>\n' +
                '        <p id="nameErr" style="color: #b1191a"></p>\n' +
                '    </div>\n' +
                '    <div class="layui-form-item" style="margin-top: 15px">\n' +
                '        <label class="layui-form-label" style="width: 117px" >输入快递单号</label>\n' +
                '        <div class="layui-input-block">\n' +
                '            <input type="text" id="logisticNum" name="logisticNum" lay-verify="title" autocomplete="off" placeholder="请输入快递单号" class="layui-input" style="width: 206px"></div>\n' +
                '        <p id="nErr" style="color: #b1191a"></p>\n' +
                '    </div>\n' +
                '    <div class="layui-form-item" style="margin-top: 15px">\n' +
                '        <label class="layui-form-label" style="width: 117px" >输入订单单号</label>\n' +
                '        <div class="layui-input-block">\n' +
                '            <input type="text" id="orderId" name="orId" lay-verify="title" autocomplete="off" placeholder="输入订单单号" class="layui-input" style="width: 206px"></div>\n' +
                '        <p id="orErr" style="color: #b1191a"></p>\n' +
                '    </div>\n' +
                '</form>\n' +
                '<script>\n' +
                '    $("#logisticNum").val(localStorage.getItem("logisticLogisticnum"))\n' +
                '    $("#orderId").val(localStorage.getItem("logisticOrderId"))\n' +
                '</script>',
                {
                    title: '修改表单',
                    type: 0,
                    skin: 'layui-layer-molv', //样式类名
                    closeBtn: 1, //显示关闭按钮
                    anim: 0,  // 动画
                    shadeClose: true, //开启遮罩关闭
                    area: ['380px', '300px'],
                }, function () {

                    // 获得公司名
                    let comName = $("#comName").val()
                    //  获得快递单号
                    let logNum = $("#logisticNum").val()
                    //  获得订单单号
                    let orderId = $("#orderId").val()

                    // 快递公司点击确定并未填数值
                    comNamejudge()
                    // 快递公司填值并移动聚焦
                    $("[name='comName']").blur(function () {
                        comNamejudge()
                    })

                    //  快递单号点击确定并未填数值
                    logisticNumjudge()
                    // 快递单号填值并移动聚焦
                    $("[name='logisticNum']").blur(function () {
                        logisticNumjudge()
                    })

                    // 订单单号点击确定未填写
                    orderIdjudge(orderId)
                    // 订单单号填值并移动聚焦
                    $("[name='orId']").blur(function () {
                        orderIdjudge()
                    })

                    //  得到快递单号对数据库进行更改
                    let logisticId = obj.data.logisticId
                    alliskey(logisticId, comName, logNum, orderId)
                }
            )
        }
    });
});

function inputvalue(value) {
    if (value === null) {
        return value = ""
    } else {
        return value
    }
}

function dlevalue(deletId) {
    // console.log("调用删除方法 -> " + deletId)
    $.getJSON("http://localhost:8080/admin/deletALogByLId", "aftSaleId=" + deletId, function (data) {
        showResult(data)
    })
}

function str(str) {
    return str.replace(/\s+/g, "")
}

function num(num) {
    let numstr = num + ''
    numstr = numstr.replace(/\s+/g, "")
    return parseInt(numstr)
}

function comNamejudge() {

    let comName = $("#comName").val()
    comName = str(comName)

    let logNum = $("#logisticNum").val()
    logNum = str(logNum)

    if (comName === "顺丰速运" || comName === "申通快递" || comName === "韵达快递") {

        $("#nameErr").html("")

        switch (comName) {
            case ("顺丰速运"):
                let sf = /^[A-Za-z0-9-]{4,35}$/
                if (sf.test(logNum)) {
                    $("#nErr").html("")
                    return true
                } else {
                    $("#nErr").html("输入有误")
                    return false
                }
            case ("申通快递"):
                let st = /^(268|888|588|688|368|468|568|668|768|868|968)[0-9]{9}$|^(11|22|40|268|888|588|688|368|468|568|668|768|868|968)[0-9]{10}$|^(STO)[0-9]{10}$|^(33)[0-9]{11}$|^(4)[0-9]{12}$|^(55)[0-9]{11}$|^(66)[0-9]{11}$|^(77)[0-9]{11}$|^(88)[0-9]{11}$|^(99)[0-9]{11}$/
                if (st.test(logNum)) {
                    $("#nErr").html("")
                    return true
                } else {
                    $("#nErr").html("输入有误")
                    return false
                }
            case ("韵达快递"):
                let yd = /^(10|11|12|13|14|15|16|17|19|18|50|55|58|80|88|66|31|77|39)[0-9]{11}$|^[0-9]{13}$/
                if (yd.test(logNum)) {
                    $("#nErr").html("")
                    return true
                } else {
                    $("#nErr").html("输入有误")
                    return false
                }
            default:
                return false
        }
    } else {
        $("#nameErr").html("输入有误或为空")
        return false
    }
}

function logisticNumjudge() {

    let comName = $("#comName").val()
    comName = str(comName)

    let logNum = $("#logisticNum").val()
    logNum = str(logNum)

    if (comName != null) {
        switch (comName) {
            case ("顺丰速运"):
                let sf = /^[A-Za-z0-9-]{4,35}$/
                if (sf.test(logNum)) {
                    $("#nErr").html("")
                    return true
                } else {
                    return false
                }
            case ("申通快递"):
                let st = /^(268|888|588|688|368|468|568|668|768|868|968)[0-9]{9}$|^(11|22|40|268|888|588|688|368|468|568|668|768|868|968)[0-9]{10}$|^(STO)[0-9]{10}$|^(33)[0-9]{11}$|^(4)[0-9]{12}$|^(55)[0-9]{11}$|^(66)[0-9]{11}$|^(77)[0-9]{11}$|^(88)[0-9]{11}$|^(99)[0-9]{11}$/
                if (st.test(logNum)) {
                    $("#nErr").html("")
                    return true
                } else {
                    $("#nErr").html("输入有误")
                    return false
                }
            case ("韵达快递"):
                let yd = /^(10|11|12|13|14|15|16|17|19|18|50|55|58|80|88|66|31|77|39)[0-9]{11}$|^[0-9]{13}$/
                if (yd.test(logNum)) {
                    $("#nErr").html("")
                    return true
                } else {
                    $("#nErr").html("输入有误")
                    return false
                }
            default:
                return false
        }
    } else {
        $("#nameErr").html("输入有误或为空")
        return false
    }
}

function orderIdjudge() {

    let orderId = $("#orderId").val()
    orderId = num(orderId)

    let ret = /^[0-9]+$/
    if (ret.test(orderId)) {
        $("#orErr").html("")
        return true
    } else {
        $("#orErr").html("输入有误")
        return false
    }
}

function alliskey(logisticId, comName, logNum, orderId) {

    if (comNamejudge() && orderIdjudge() && logisticNumjudge()) {

        logNum = str(logNum)
        orderId = num(orderId)

        $.ajax({
            url: "http://localhost:8080/admin/updateALog",
            data: "logisticId=" + logisticId + "&logisticLogisticnum=" + logNum + "&logisticOrderId=" + orderId,
            dataType: "json",
            type: "get",
            success: function (data) {
                showResult(data)
            }
        })
    }
}

function showResult(data) {
    if (data.code === 0) {
        layer.alert('<div style="height: 45px;text-align:center;line-height: 45px">操作成功</div>', {
            title: '提示',
            skin: 'layui-layer-lan'
            , closeBtn: 0
        }, function (index) {
            if (localStorage.getItem("condition") !== $("#logall").html()) {
                layer.close(index);
                layuireload()
            } else {
                layer.close(index);
                allreload()
            }
        })
    } else {
        layer.alert('<div style="height: 45px;text-align:center;line-height: 45px">操作失败</div>', {
            title: '提示',
            skin: 'layui-layer-lan'
            , closeBtn: 0
        }), function (index) {
            layer.close(index)
        }
    }
}

$("#wdel").click(function () {
    // 未发货
    localStorage.setItem("condition", $("#wdel").html())
    hdcolorno()
    hdcolorclick("#wdel")
    mylayuireload()
})

$("#tran").click(function () {
    // 运输中
    localStorage.setItem("condition", $("#tran").html())
    hdcolorno()
    hdcolorclick("#tran")
    mylayuireload()
})

$("#wpick").click(function () {
    // 待取件
    localStorage.setItem("condition", $("#wpick").html())
    hdcolorno()
    hdcolorclick("#wpick")
    mylayuireload()
})

$("#logall").click(function () {
    // 全部
    localStorage.setItem("condition", $("#logall").html())
    hdcolorno()
    hdcolorclick("#logall")
    myallreload()
})

function layuireload() {
    layui.table.reload('logisticId', {
        url: 'http://localhost:8080/admin/selectlogistic'
        , page: {
            cuur: $(".layui-laypage-skip .layui-input").val()
        }
        , where:
            {
                orderState: localStorage.getItem("condition")
            }
    })
}

function mylayuireload() {
    layui.table.reload('logisticId', {
        url: 'http://localhost:8080/admin/selectlogistic'
        , page: {
            curr: 1
        }
        , where:
            {
                orderState: localStorage.getItem("condition")
            }
    })
}

function allreload() {
    layui.table.reload('logisticId', {
        url: 'http://localhost:8080/admin/selealoglui'
        , page: {
            cuur: $(".layui-laypage-skip .layui-input").val()
        }
    });
}

function myallreload() {
    layui.table.reload('logisticId', {
        url: 'http://localhost:8080/admin/selealoglui'
        , page: {
            curr: 1
        }
    });
}

function hdcolorno() {
    $('#logall').css('color', '')
    $('#wdel').css('color', '')
    $('#tran').css('color', '')
    $('#wpick').css('color', '')
}

function hdcolorclick(htvalue) {
    $(htvalue).css('color', '#43A2FF')
}